package com.advertisementsystem.Controller;


import com.advertisementsystem.Servie.SystemMonitorService;
import com.advertisementsystem.entity.SysAlert;
import com.advertisementsystem.entity.SysMetrics;
import com.advertisementsystem.response.PageResult;
import com.advertisementsystem.Exception.ResponseResult;
import com.advertisementsystem.vo.SystemHealthReport;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/monitor")
@Slf4j
public class SystemMonitorController {

    @Autowired
    private SystemMonitorService monitorService;

    @GetMapping("/metrics/current")

    @PreAuthorize("hasRole('ADMIN')")
    public ResponseResult<SysMetrics> getCurrentMetrics() {
            SysMetrics metrics = monitorService.getCurrentMetrics();
            return ResponseResult.success(metrics);
    }

    @GetMapping("/metrics/history")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseResult<List<SysMetrics>> getHistoryMetrics(
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
            log.info("{} {}", startTime, endTime);
            List<SysMetrics> metrics = monitorService.getHistoryMetrics(startTime, endTime);
            return ResponseResult.success(metrics);

    }

    @GetMapping("/health")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseResult<SystemHealthReport> getHealthReport() {
            SystemHealthReport report = monitorService.generateHealthReport();
            return ResponseResult.success(report);

    }

    @GetMapping("/alerts")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseResult<PageResult<SysAlert>> getAlerts(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
            PageResult<SysAlert> alerts = monitorService.getAlerts(pageNum, pageSize);
            return ResponseResult.success(alerts);

    }
}